package yams.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import yams.common.IRepository;
import yams.domain.UserEntity;
import yams.repository.IUserRepository;
import yams.service.IUserService;

/**
 * 会员服务
 * Created by Luffy on 2017/07/29.
 */
@Service("userService")
public class DefaultUserService implements IUserService {

    private final IUserRepository userRepository;
    private final JdbcTemplate jdbcTemplate;

    private final PlatformTransactionManager transactionManager;

    @Autowired
    public DefaultUserService(IUserRepository userRepository,
                              JdbcTemplate jdbcTemplate,PlatformTransactionManager transactionManager) {
        this.userRepository = userRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.transactionManager = transactionManager;
    }

    @Override
    public IRepository<UserEntity> getRepository() {
        return userRepository;
    }


    @Override
    public UserEntity autoUserCode(UserEntity userEntity) {
        String sql="select max(code) from t_user WHERE code LIKE '000%'";
        TransactionTemplate transactionTemplate=new TransactionTemplate(transactionManager);
        return transactionTemplate.execute(status ->{
            String maxCode = jdbcTemplate.queryForObject(sql,String.class);
            int a=Integer.parseInt(maxCode)+1;
            String str=String.valueOf(a),num="";
            if(str.length()<8){
                for (int i=0;i<8-str.length();i++){
                    num=num+0;
                }
            }
            userEntity.setCode(num+str);
            return userEntity;
        });
    }
}
